var falert = function(msg, url) {
    layer.msg(msg, {time: 1500}, function(){
        if (url) {
            location.href = url;
        }
    });
};
var common = function($) {
function ajax(o) {
    try {
        var dtd = $.Deferred(),
        index = !o.unlock && lockWindow(),
        setting = {
            dataType: o.dataType || 'JSON',
            url: o.url || '/wechat.api',
            type: o.type || 'POST',
            timeout: o.timeout || 6e4,
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Request-Type", "ajax-request"),
                o.beforeSend && o.beforeSend();
            },
            success: function(back_data) {
                try {
                    if (back_data.status == '5001') {
                        falert(back_data.msg,'/pay/paylogin');
                    }else if(back_data.status == '5002'){
                        falert(back_data.msg,'/');
                    }else if(back_data.status == '5003'){
                        falert(back_data.msg,'/pay/paylogin');
                    }
                    else if(back_data.status == '5004'){
                        falert(back_data.msg,'/pay/paylogin');
                    }
                    o.success && o.success(back_data),
                    dtd.resolve();
                } catch(e) {
                    dtd.reject();
                } finally {
                    unlockWindow(index)
                }
            },
            error: function(error_msg, textStatus) {
                var tipsTxt = error_msg.statusText,
                status_code = error_msg.status;
                switch (tipsTxt = "timeout" == tipsTxt ? "请求超时": tipsTxt, status_code) {
                    case 404:
                        falert("文件不存在!");
                        break;
                    case 500:
                        falert("服务器产生内部错误!");
                        break;
                    case 502:
                        falert("网关错误，服务请求超时!");
                        break;
                    case 504:
                        falert("请求超时!")
                }
                o.error && o.error.apply(o, arguments),
                unlockWindow(index),
                dtd.reject();
            },
            complete: function(XMLHttpRequest, textStatus) {
                if (null != XMLHttpRequest) {
                    if (2 == XMLHttpRequest.status)
                        return falert("文件不存在!"),!1;
                    if (3 == XMLHttpRequest.status || "timeout" == textStatus)
                        return falert("服务器无响应!"),!1;
                    if (200 == XMLHttpRequest.status);
                    else {
                        if (400 <= XMLHttpRequest.status && 404 > XMLHttpRequest.status)
                            return falert("错误请求!"),!1;
                        if (404 == XMLHttpRequest.status)
                            return falert("文件不存在!"),!1;
                        if (500 == XMLHttpRequest.status || 504 < XMLHttpRequest.status)
                            return falert("服务器产生内部错误!"),!1;
                        if (502 == XMLHttpRequest.status)
                            return falert("网关错误，服务请求超时!"),!1;
                        if (504 == XMLHttpRequest.status)
                            return falert("请求超时!"),!1
                    }
                }
            }
        }
        d = $.extend({},
        o.data);
        setting.data = {
            datas: JSON.stringify(d)
        },
        $.ajax(setting);
    } catch(e) {
        falert(e.message);
    }
    return dtd;
}
function lockWindow(type) {
    return layer.load(type || 0, {
        shade: [0, 'black']
    })
}
function unlockWindow(index) {
    index && layer.close(index)
}
function countDown(o, countDownTime, msg) {
    o = $(o), o.isCountingDown() || (countDownTime = countDownTime || 60, msg = void 0 === msg ? "秒后重发" : msg, function counting(o) {
        var countDownId = null;
        if (0 == countDownTime) clearCountDown(o);
        else {
            countDownId = setTimeout(function() {
                counting(o)
            }, 1e3);
            var f = o.data("countDownId", countDownId).prop("disabled", !0).removeClass("get-code").addClass("reset-code")[o.is("input") && "val" || "html"];
            f && f.call(o, countDownTime + msg), countDownTime--
        }
    }(o))
}
function clearCountDown(o, msg) {
    o = $(o), clearTimeout(o.data("countDownId"));
    var f = o.prop("disabled", !1).removeClass("reset-code").addClass("get-code").removeData("countDownId")[o.is("input") && "val" || "html"];
    f && f.call(o, void 0 === msg ? "获取验证码" : msg)
}
function isCountingDown(obj) {
    return !!$(obj).data("countDownId")
}
function formatTemplateStr(dta, tmpl, flag) {  
    var reg = flag ? /{(\w+)}/g : /<em>{(\w+)}<\/em>/g;
    var format = {
        name: function (x) { return x; }
    };
    return tmpl.replace(reg, function (m1, m2) {
        if (!m2) return "";
        return (format && format[m2]) ? format[m2](dta[m2]) : dta[m2];
    });  
}
function formatTemplate(dta, html, flag) {
    var str='';
    flag = flag || false;
    if($.isArray(dta)){
        var arr = [];  
        $.each(dta, function(i, o) {   
            arr.push(formatTemplateStr(o, html, flag));  
        });
        str = arr.join('');
    }else{
        str = formatTemplateStr(dta, html, flag);
    }
    return str;
}
function formatMoney(str, o) {
    o = o || {};
    var formatStr = "",
    max = o.hasOwnProperty("max") ? o.max: 14;
    o.hasOwnProperty("toFixed") ? o.toFixed: 2;
    if (str = (str + "").replace(/,|\s/g, ""), !isNaN(str) && parseFloat(str, 10) > 0) {
        var arr = str.split("."),
        integer = arr[0],
        ilen = integer.length,
        offset = ilen % 3;
        if (max >= ilen) {
            var match, i = 0,
            reg = /\d{3}?/g;
            for (reg.lastIndex = offset, formatStr = integer.substring(0, offset); null != (match = reg.exec(integer));) formatStr = formatStr + (0 == offset && 0 == i++?"": ",") + match[0];
            return formatStr + "." + ((arr[1] || "") + "00").substring(0, 2)
        }
    }
    return ! 1
}
function deFormatMoney(str) {
    return parseFloat(str.replace(/\s|,/g, ""), 10)
}
function formatCard(cardstr){
    if ("" != cardstr) {
        var reg = /^(\d{4})(\d{4})?(\d{4})?(\d{4})?(\d*)$/,
        arr = [];
        if (reg.test(cardstr)) {
            arr = [RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4, RegExp.$5];
            for (var str = arr[0], i = 1, len = arr.length; len > i; i++) arr[i] && (str += " " + arr[i]);
            cardstr = str;
        }
    }
    return cardstr;
}
function formatFormData(id) { 
    var d = new Object;
    var t = $('#'+id+' input,#'+id+' select').serializeArray();
    $.each(t, function(i, o) {
        d[o.name] = o.value;
    });
    return d;
}
function get(key) { 
    var aQuery = window.location.href.split("?");  //取得Get参数
    var aGET = new Array();
    if (aQuery.length > 1){
        var aBuf = aQuery[1].split("&");
        for (var i = 0, iLoop = aBuf.length; i < iLoop; i++){
            var aTmp = aBuf[i].split("=");  //分离key与Value
            aGET[aTmp[0]] = aTmp[1];
        }
    }
    return aGET[key];
}
function compress(obj, callback) {
    var file = obj.files[0];
    if (!/image\/\w+/.test(file.type)) {
        falert("请上传正确的图片资料");
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    $(reader).load(function() {
        var image = new Image();
        image.src = this.result;
        image.onload = function(){
            if(this.width > 1000 || this.height > 1000){
                var square = 1000,imageWidth,imageHeight,offsetX = 0,offsetY = 0;
                if (this.width > this.height) {
                    imageWidth = Math.round(square * this.width / this.height);
                    imageHeight = square;
                } else {
                    imageHeight = Math.round(square * this.height / this.width);
                    imageWidth = square;
                }
                var canvas = document.createElement('canvas');
                canvas.width = imageWidth;
                canvas.height = imageHeight;
                var context = canvas.getContext('2d');
                context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                var data = canvas.toDataURL(file.type);
                //压缩完成执行回调  
                callback([file.type,data]);
            }else{
                callback([file.type,reader.result]);
            }
        }
    });
}  
function CheckForm(chainMode) {
    this.init(chainMode)
}
$.fn.countDown = function(countDownTime, msg) {
    return this.each(function() {
        countDown(this, countDownTime, msg)
    })
},
$.fn.clearCountDown = function(countDownTime, msg) {
    return this.each(function() {
        clearCountDown(this, countDownTime, msg)
    })
},
$.fn.isCountingDown = function(countDownTime) {
    return isCountingDown(this, countDownTime)
},
CheckForm.prototype = {
    init: function(chainMode) {
        return this.chainMode = chainMode, this.returnValue = this.value = !0, this
    },
    validate: function(fun, args) {
        if (this.returnValue === !1 || !this.value && !this.chainMode) return this;
        var re = fun.apply(this, args);
        return this.value = re && this.value, this
    },
    regExp: function() {
        return this.validate(function(reg, str, callback) {
            var re = reg.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re)), re
        }, arguments)
    },
    checkUser: function() {
        return this.validate(function(str, callback) {
            var re = /^[a-zA-Z]\w{3,15}$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "用户名输入错误，请重新输入")), re
        }, arguments)
    },
    checkMobile: function() {
        return this.validate(function(str, callback) {
            var re = /^1\d{10}$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "请输入正确的手机号码")), re
        }, arguments)
    },
    checkPhone: function() {
        return this.validate(function(str, callback) {
            var re = /^0\d{2,3}-?\d{7,8}$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "电话号码输入错误，请重新输入")), re
        }, arguments)
    },
    checkEmail: function() {
        return this.validate(function(str, callback) {
            var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "邮箱输入错误，请重新输入")), re
        }, arguments)
    },
    checkPwd: function() {
        return this.validate(function(str, callback) {
            var re = /^\w{6,20}$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "密码请输入6-20位数字或字母")), re
        }, arguments)
    },
    checkName: function() {
        return this.validate(function(str, callback) {
            var re = /^([\u4e00-\u9fa5]){1,7}(?:·[\u4e00-\u9fa5]{1,7})*$/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "请输入正确的姓名")), re
        }, arguments)
    },
    checkId: function() {
        return this.validate(function(str, callback) {
            var re = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
            return "function" == typeof callback && (this.returnValue = callback(re, re || "请输入正确的身份证号码")), re
        }, arguments)
    },
    checkIdCard: function() {
        return this.validate(function(id, callback) {
            var date, Ai, verify = "10x98765432",
                Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
                area = ["", "", "", "", "", "", "", "", "", "", "", "北京", "天津", "河北", "山西", "内蒙古", "", "", "", "", "", "辽宁", "吉林", "黑龙江", "", "", "", "", "", "", "", "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", "", "", "", "河南", "湖北", "湖南", "广东", "广西", "海南", "", "", "", "重庆", "四川", "贵州", "云南", "西藏", "", "", "", "", "", "", "陕西", "甘肃", "青海", "宁夏", "新疆", "", "", "", "", "", "台湾", "", "", "", "", "", "", "", "", "", "香港", "澳门", "", "", "", "", "", "", "", "", "国外"],
                re = id.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
            if (null == re) return !1;
            if (re[1] >= area.length || "" == area[re[1]]) return !1;
            12 == re[2].length ? (Ai = id.substr(0, 17), date = [re[9], re[10], re[11]].join("-")) : (Ai = id.substr(0, 6) + "19" + id.substr(6), date = ["19" + re[4], re[5], re[6]].join("-"));
            for (var sum = 0, i = 0; 16 >= i; i++) sum += Ai.charAt(i) * Wi[i];
            return Ai += verify.charAt(sum % 11), re = 15 == id.length || 18 == id.length && id.toLowerCase() == Ai.toLowerCase(), "function" == typeof callback && (this.returnValue = re ? callback(re, parseInt(15 == id.length ? id.substr(14, 1) : id.substr(16, 1)) % 2 == 0 ? "女" : "男", date) : callback(re, "请输入正确的身份证号码")), re
        }, arguments)
    },
    checkCard: function() {
        return this.validate(function(str, callback) {
            str = str.replace(/\s*/g, "");
            var re = /(^\d{13,}$)/.test(str),
                errorMsg = "" == str ? "请输入银行卡号" : isNaN(str) ? "银行卡信息输入有误,请重新输入" : str.length < 13 ? "银行卡号不能少于13位" : "银行卡信息输入有误,请重新输入";
            return "function" == typeof callback && (this.returnValue = callback(re, re ? "" : errorMsg)), re
        }, arguments)
    },
    luhm: function() {
        return this.validate(function(bankno, callback) {
            var re;
            if (bankno) {
                bankno += "";
                for (var odd = 0, even = 0, i = bankno.length - 1, j = 1; i >= 0; i--) {
                    var v = parseInt(bankno.charAt(i));
                    j % 2 !== 0 ? odd += v : even += 2 * v - 9 > 0 ? 2 * v - 9 : 2 * v, j++
                }
                re = (odd + even) % 10 === 0
            }
            return "function" == typeof callback && (this.returnValue = callback(re, re ? "" : "请输入正确的银行卡号")), re
        }, arguments)
    },
    checkTime: function() {
        return this.validate(function(str, callback) {
            var re = /^(\d{4})-(\d{2})-(\d{2})$/.test(str);
            if (RegExp.$2 > 12 || RegExp.$3 > 31) {
                re = false;
            }
            return "function" == typeof callback && (this.returnValue = callback(re, re || "请输入正确的时间格式，如：XXXX-XX-XX")), re
        }, arguments)
    }
};
return {
    checkForm: function(chainMode) {
        var checkForm = new CheckForm;
        return checkForm.init(chainMode)
    },
    ajax: ajax,
    lock: lockWindow,
    unlock: unlockWindow,
    countDown: countDown,
    clearCountDown: clearCountDown,
    isCountingDown: isCountingDown,
    formatMoney: formatMoney,
    deFormatMoney: deFormatMoney,
    formatCard: formatCard,
    formatTemplate: formatTemplate,
    formatFormData:formatFormData,
    get:get,
    compress:compress,
};
} (jQuery);


/**
 * 正则校验
 */
var Regexs = {
    email: (/^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/i),//邮箱  
    phone: (/^0[0-9]{2,3}[2-9][0-9]{6,7}$/),//座机手机号码  
    ydphpne: (/^((13[4-9])|(15[012789])|147|182|187|188)[0-9]{8}$/),//移动手机号码  
    allphpne: (/^1\d{10}$/),//匹配所有手机号码，1开头后面任意10位
    // allphpne: (/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[0-9])\d{8}$/),//所有手机号码  新
    ltphpne: (/^((13[0-2])|(15[56])|(186)|(145))[0-9]{8}$/),//联通手机号码  
    dxphpne: (/^((133)|(153)|(180)|(189))[0-9]{8}$/),//电信手机号码  
    url: (/^http:\/\/([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}(:\d+)?\/[0-9a-z%\-_\/\.]+/i),//网址  
    num: (/[^0-9]/),//数字  
    cnum: (/[^0-9a-zA-Z_.-]/),  
    photo: (/\.jpg$|\.jpeg$|\.gif$|\.png$|\.bmp$/i),//图片格式  
    row: (/\n/ig),
    invalidChar:(/^(([^\^\.<>%&',;=?$"':#@!~\]\[{}\\/`\|])*)$/),
    idCard:(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/),//身份证号
    price:(/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/)//金额
};



/**
 * 获取本周、本季度、本月、上月的开始日期、结束日期
 */
var now = new Date(); //当前日期
var nowDayOfWeek = now.getDay(); //今天本周的第几天
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0; //

var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
var lastYear = lastMonthDate.getYear();
var lastMonth = lastMonthDate.getMonth();

//格式化日期：yyyy-MM-dd
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth()+1;
    var myweekday = date.getDate();

    if(mymonth < 10){
        mymonth = "0" + mymonth;
    }
    if(myweekday < 10){
        myweekday = "0" + myweekday;
    }
    return (myyear+"-"+mymonth + "-" + myweekday);
}
//获得某月的天数
function getMonthDays(myMonth){
    var monthStartDate = new Date(nowYear, myMonth, 1);
    var monthEndDate = new Date(nowYear, myMonth + 1, 1);
    var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
    return days;
}

//获得本周的开始日期
function getTodayDate() {
    var today = new Date(nowYear, nowMonth, nowDay);
    return formatDate(today);
}
//获得本周的开始日期
function getWeekStartDate() {
    var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
    return formatDate(weekStartDate);
}

//获得本周的结束日期
function getWeekEndDate() {
    var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
    return formatDate(weekEndDate);
}

//获得本月的开始日期
function getMonthStartDate(){
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    return formatDate(monthStartDate);
}

//获得本月的结束日期
function getMonthEndDate(){
    var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
    return formatDate(monthEndDate);
}